package com.kern.academic.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kern.academic.bean.ResponseResult;
import com.kern.academic.dto.RightsDTO;
import com.kern.academic.dto.RightsNode;
import com.kern.academic.entity.XRights;
import com.kern.academic.service.IRightsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.List;

/**
 * Created by caoshi at 7:51 2021-07-13
 */
@RestController
@RequestMapping("/rights")
public class RightsController {

    private static Logger logger = LoggerFactory.getLogger(RightsController.class);

    @Autowired
    private IRightsService rightsService;


    @RequestMapping("/listAllRights")
    public ResponseResult listAllRights() {
        List<RightsDTO> xRights = rightsService.listAll();
        return ResponseResult.ok("查询所有权限成功!", xRights);
    }

    @RequestMapping("/listRightsByRoleId")
    public ResponseResult listRightsByRoleId(@RequestBody JSONObject param) {
        String roleId = param.getString("roleId");
        List<RightsNode> rightsArray;
        try {
            rightsArray = rightsService.listRightsByRoleId(roleId);
            logger.debug("==rightsArray: {} ==", rightsArray);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
            return ResponseResult.fail("查询权限失败!");
        }
        return ResponseResult.ok("success", rightsArray);
    }


    /**
     * 授权
     * @param authInfo
     * @return
     */
    @RequestMapping("/authorize")
    public ResponseResult authorize(@RequestBody JSONObject authInfo) {
        logger.info("=角色授权入参 = {}", authInfo);
        String roleId = authInfo.getString("roleId");
        JSONArray rightsIds = authInfo.getJSONArray("rightsIds");
        return rightsService.authorize(roleId, rightsIds);
    }

    @RequestMapping("/update")
    public ResponseResult update(@RequestBody XRights rights) {
        System.out.println("rights = " + rights);

        return ResponseResult.ok("修改权限信息成功");
    }




}
